﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZipTool.Properties;

namespace ZipTool
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。拖动待压缩或解压的文件至此应用，即可进行压缩或解压。\r\n通过cmd调用时，传参数PASS:***可指定密码
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                Depends.Export(args);   // 解压依赖dll
                AnalyseArgs(args);      // 解析参数信息
                process(Args, Password);// 执行压缩解压
            }
            else MessageBox.Show("拖动待压缩或解压的文件至此应用，即可进行压缩或解压。\r\n通过cmd调用时，传参数PASS:***可指定密码！");
        }

        /// <summary>
        /// 执行压缩解压逻辑
        /// </summary>
        private static void process(string[] args, string password)
        {
            // 执行逻辑
            if (args != null && args.Length > 0)
            {
                // 进行压缩、解压
                Tools.ZipTool.Process(Args, Password);

                //// 删除临时文件
                //deletFile("ICSharpCode.SharpZipLib.dll");
                //deletFile("Tools.dll");
                string[] files = new string[] { "ICSharpCode.SharpZipLib.dll", "Tools.dll" };
                AutoDelet.deletFiles(files);
            }
        }

        private static string Password = null;  // 压缩解压密码
        private static string[] Args = null;    // 其他参数
        /// <summary>
        /// 解析应用参数信息
        /// </summary>
        private static void AnalyseArgs(string[] args)
        {
            // 解析参数信息
            List<string> argList = new List<string>();
            if (args != null && args.Length > 0)
            {
                foreach (string arg0 in args)
                {
                    string arg = arg0.Trim();
                    if (arg.StartsWith("PASS:")) Password = arg.Substring("PASS:".Length);
                    else argList.Add(arg);
                }
            }
            Args = argList.ToArray();
        }

    }

    public class Depends
    {
        /// <summary>
        /// 解压依赖dll，后重启应用
        /// </summary>
        public static void Export(string[] args)
        {
            if (args != null && args.Length > 0)
            {
                string ZipLib = curDir() + "ICSharpCode.SharpZipLib.dll";
                string Tool = curDir() + "Tools.dll";
                if (!File.Exists(ZipLib) || !File.Exists(Tool))
                {
                    if (!File.Exists(ZipLib)) SaveFile(Resources.ICSharpCode_SharpZipLib, ZipLib);
                    if (!File.Exists(Tool)) SaveFile(Resources.Tools, Tool);

                    //string Arg = ComBineArgs(args);
                    //System.Diagnostics.Process.Start(curExecutablePath(), Arg);
                    //System.Environment.Exit(0); //退出
                }
            }
        }

        /// <summary>
        /// 合并参数为单个串
        /// </summary>
        private static string ComBineArgs(string[] args)
        {
            string str = "";
            foreach (string arg0 in args)
            {
                string arg = arg0.Trim().Trim('"');
                str += " \"" + arg + "\"";
            }
            return str.Substring(1);
        }

        /// <summary>
        /// 获取当前运行路径
        /// </summary>
        public static string curDir()
        {
            return AppDomain.CurrentDomain.BaseDirectory;
        }

        /// <summary>
        /// 获取当前运行Exe的路径
        /// </summary>
        public static string curExecutablePath()
        {
            return System.Windows.Forms.Application.ExecutablePath;
        }

        /// <summary>
        /// 保存Byte数组为文件
        /// </summary>
        public static void SaveFile(Byte[] array, string path, bool repalce = false)
        {
            if (repalce && File.Exists(path)) File.Delete(path);    // 若目标文件存在，则替换
            if (!File.Exists(path))
            {
                // 创建输出路径
                String dir = Path.GetDirectoryName(path);

                // 创建输出流
                FileStream fs = new FileStream(path, FileMode.Create);

                //将byte数组写入文件中
                fs.Write(array, 0, array.Length);
                fs.Close();
            }
        }

        ///// <summary>
        ///// 删除文件
        ///// </summary>
        //public static void deletFile(string Name)
        //{
        //    string path = AppDomain.CurrentDomain.BaseDirectory + Name;
        //    if (File.Exists(path)) File.Delete(path);
        //}
    }

    public class AutoDelet
    {
        /// <summary>
        /// 删除文件
        /// </summary>
        public static void deletFiles(string[] Names)
        {
            try
            {
                //Set ws = CreateObject("Wscript.Shell") 
                //WScript.sleep 5000
                //ws.run "cmd /c ?> $",vbhide
                //ws.run "cmd /c del $",vbhide
                //ws.run "cmd /c ?> $.vbs",vbhide
                //ws.run "cmd /c del $.vbs",vbhide

                string vbsName = "Clear.vbs";
                StringBuilder Str = new StringBuilder();
                Str.AppendLine("Set ws = CreateObject(\"Wscript.Shell\")");
                Str.AppendLine("WScript.sleep 1000");
                Str.AppendLine("ws.run \"cmd /c del " + vbsName + "\",vbhide");

                string dir = AppDomain.CurrentDomain.BaseDirectory;
                foreach (string name in Names)
                {
                    if (File.Exists(dir + name)) Str.AppendLine("ws.run \"cmd /c del " + name + "\",vbhide");
                }
                string data = Str.ToString();

                SaveFile(data, dir + vbsName);
                System.Diagnostics.Process.Start(dir + vbsName);

                System.Environment.Exit(0); //退出
            }
            catch (Exception) { }
        }

        /// <summary>  
        /// 保存数据data到文件处理过程，返回值为保存的文件名  
        /// </summary>  
        private static String SaveFile(String data, String filePath)
        {
            System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePath, false, Encoding.Default);     //文件已覆盖方式添加内容  

            file1.Write(data);                                                              //保存数据到文件  

            file1.Close();                                                                  //关闭文件  
            file1.Dispose();                                                                //释放对象  

            return filePath;
        }
    }

}
